﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Security.Cryptography;
using System.IO;

namespace StoragePeriod.Web.Common
{
    public class UtilityUI
    {

        public static void Alert(UpdatePanel upanel, string msg)
        {
            var script = string.Format("alert('{0}');sp.init();", msg);
            ScriptManager.RegisterClientScriptBlock(upanel, typeof(Page), "alertMsg", script, true);
        }

        public static void Init(UpdatePanel upanel)
        {
            var script = string.Format("sp.init();");
            ScriptManager.RegisterClientScriptBlock(upanel, typeof(Page), "alertMsg", script, true);
        }

        public static void Load(UpdatePanel upanel, string fuName)
        {
            var script = string.Format("{0};sp.init();", fuName);
            ScriptManager.RegisterClientScriptBlock(upanel, typeof(Page), "alertMsg", script, true);
        }


        #region cookie操作

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        public static void WriteCookie(string strName, string strValue)
        {
            WriteCookie(strName, strValue, "", "");
        }

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="domain">域</param>
        /// <param name="path">路径</param>
        public static void WriteCookie(string strName, string strValue, string domain, string path)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            if (!string.IsNullOrEmpty(path)) cookie.Path = path;
            if (!string.IsNullOrEmpty(domain)) cookie.Domain = domain;
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="strValue">过期时间(分钟)</param>
        public static void WriteCookie(string strName, string strValue, int expires)
        {
            WriteCookie(strName, strValue, expires, "", "/");
        }

        /// <summary>
        /// /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="expires">过期时间(分钟)</param>
        /// <param name="domain">域</param>
        /// <param name="path">路径</param>
        public static void WriteCookie(string strName, string strValue, int expires, string domain, string path)
        {
            HttpCookie cookie = HttpContext.Current.Response.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            cookie.Expires = DateTime.Now.AddMinutes(expires);
            if (!string.IsNullOrEmpty(path)) cookie.Path = path;
            if (!string.IsNullOrEmpty(domain)) cookie.Domain = domain;
            HttpContext.Current.Response.AppendCookie(cookie);

        }

        /// <summary>
        /// 读cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <returns>cookie值</returns>
        public static string GetCookie(string strName)
        {
            try
            {
                if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
                {
                    return HttpContext.Current.Request.Cookies[strName].Value.ToString();
                }
            }
            catch
            {
            }

            return "";
        }
        #endregion

        #region 数字处理

        /// <summary>
        /// 数字处理
        /// </summary>
        /// <param name="old">要处理的数字</param>
        /// <param name="No">保留小数点位数</param>
        /// <param name="type">1：全部舍入、2：全部进1、3：四舍五入</param>
        /// <returns></returns>
        public static decimal GetMathResult(decimal old, int No, int type)
        {
            decimal tempNum = 1;
            if (type == 3) return GetRound(old, No);
            if (No > 0) tempNum = Convert.ToInt32(Math.Pow(10, No));
            old = old * tempNum;
            old = Math.Truncate(old);
            old = old / tempNum;
            if (type == 1) return old;
            return old + 1 / tempNum;
        }

        /// <summary>
        /// 四舍五入
        /// </summary>
        /// <param name="dblnum"></param>
        /// <param name="numberprecision"></param>
        /// <returns></returns>
        private static decimal GetRound(decimal dblnum, int numberprecision)
        {
            int tmpNum = dblnum > 0 ? 5 : -5;
            decimal dblreturn = Math.Truncate(dblnum * Convert.ToDecimal(Math.Pow(10, numberprecision + 1))) + tmpNum;
            dblreturn = Math.Truncate(dblreturn / 10) / Convert.ToDecimal(Math.Pow(10, numberprecision));
            return dblreturn;
        }
        
        #endregion

        #region 加解密


        const string KEY_64 = "beijitzA";//注意了，是8个字符，64位
        const string IV_64 = "beijitzA";
        /// <summary>
        /// MD5逆解密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Decode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }

        /// <summary>
        /// MDB可逆加密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Encode(string data)
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(data);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);

        }

        #endregion
    }
}